"""
主页面路由 - 简化版
"""
from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for
from flask_login import login_required, current_user
from sqlalchemy import func, or_, and_

from app.extensions import db
from app.models.customer import Customer
from app.models.staff import Staff
from app.models.negotiation import Negotiation

main_bp = Blueprint('main', __name__)


@main_bp.route('/')
def index():
    if current_user.is_authenticated:
        return redirect(url_for('main.dashboard'))
    return redirect(url_for('auth.login'))


@main_bp.route('/dashboard')
@login_required
def dashboard():
    """系统主页 - 统计数据和图表"""
    # 获取统计数据
    total_customers = Customer.query.count()
    current_year_customers = Customer.query.filter(
        func.strftime('%Y', Customer.created_at) == str(datetime.now().year)
    ).count()
    
    total_staff = Staff.query.count()
    current_year_staff = Staff.query.filter(
        func.strftime('%Y', Staff.created_at) == str(datetime.now().year)
    ).count()
    
    online_negotiations = Negotiation.query.filter(
        Negotiation.category == '线上合作商谈',
        func.strftime('%Y', Negotiation.start_time) == str(datetime.now().year)
    ).count()
    
    offline_negotiations = Negotiation.query.filter(
        Negotiation.category == '线下合作商谈',
        func.strftime('%Y', Negotiation.start_time) == str(datetime.now().year)
    ).count()
    
    # 生成图表数据
    charts_data = generate_dashboard_charts()
    
    return render_template('main/dashboard.html',
                         total_customers=total_customers,
                         current_year_customers=current_year_customers,
                         total_staff=total_staff,
                         current_year_staff=current_year_staff,
                         online_negotiations=online_negotiations,
                         offline_negotiations=offline_negotiations,
                         charts_data=charts_data)


def generate_dashboard_charts():
    """生成仪表板图表数据"""
    try:
        # 获取当前年份的月度数据
        current_year = datetime.now().year
        months = list(range(1, 13))
        month_names = ['1月', '2月', '3月', '4月', '5月', '6月', 
                       '7月', '8月', '9月', '10月', '11月', '12月']
        
        # 客户数量变化（累计）
        customer_data = []
        for month in months:
            # 计算截止到该月的累计客户数量
            cumulative_count = Customer.query.filter(
                or_(
                    func.strftime('%Y', Customer.created_at) < str(current_year),
                    and_(
                        func.strftime('%Y', Customer.created_at) == str(current_year),
                        func.strftime('%m', Customer.created_at) <= f'{month:02d}'
                    )
                )
            ).count()
            customer_data.append(cumulative_count)
        
        # 线上商谈次数变化
        online_data = []
        for month in months:
            count = Negotiation.query.filter(
                Negotiation.category == '线上合作商谈',
                func.strftime('%Y', Negotiation.start_time) == str(current_year),
                func.strftime('%m', Negotiation.start_time) == f'{month:02d}'
            ).count()
            online_data.append(count)
        
        # 线下商谈次数变化
        offline_data = []
        for month in months:
            count = Negotiation.query.filter(
                Negotiation.category == '线下合作商谈',
                func.strftime('%Y', Negotiation.start_time) == str(current_year),
                func.strftime('%m', Negotiation.start_time) == f'{month:02d}'
            ).count()
            offline_data.append(count)
    
        # 简化的图表数据，用于前端Chart.js渲染
        return {
            'customer_chart': {
                'labels': month_names,
                'data': customer_data,
                'title': '客户总量年度变化'
            },
            'online_chart': {
                'labels': month_names,
                'data': online_data,
                'title': '线上商谈年度变化'
            },
            'offline_chart': {
                'labels': month_names,
                'data': offline_data,
                'title': '线下商谈年度变化'
            }
        }
    except Exception as e:
        print(f"生成图表数据时出错: {e}")
        # 返回空数据作为fallback
        month_names = ['1月', '2月', '3月', '4月', '5月', '6月', 
                       '7月', '8月', '9月', '10月', '11月', '12月']
        empty_data = [0] * 12
        return {
            'customer_chart': {
                'labels': month_names,
                'data': empty_data,
                'title': '客户总量年度变化'
            },
            'online_chart': {
                'labels': month_names,
                'data': empty_data,
                'title': '线上商谈年度变化'
            },
            'offline_chart': {
                'labels': month_names,
                'data': empty_data,
                'title': '线下商谈年度变化'
            }
        }


# 重定向路由 - 为向后兼容保留
@main_bp.route('/customer_management')
@login_required
def customer_management():
    """客户管理页面 - 重定向到新路由"""
    return redirect(url_for('customer.customer_management'))


@main_bp.route('/staff_management')
@login_required
def staff_management():
    """人员管理页面 - 重定向到新路由"""
    return redirect(url_for('staff.staff_management'))


@main_bp.route('/negotiation_list')
@login_required
def negotiation_list():
    """商谈列表页面 - 重定向到新路由"""
    return redirect(url_for('negotiation.negotiation_list'))


@main_bp.route('/stats_by_staff')
@login_required
def stats_by_staff():
    """按员工统计 - 重定向到新路由"""
    return redirect(url_for('statistics.stats_by_staff'))


@main_bp.route('/stats_by_customer')
@login_required
def stats_by_customer():
    """按客户统计 - 重定向到新路由"""
    return redirect(url_for('statistics.stats_by_customer'))


@main_bp.route('/stats_by_position')
@login_required
def stats_by_position():
    """按职务统计 - 重定向到新路由"""
    return redirect(url_for('statistics.stats_by_position'))


@main_bp.route('/weekly_ongoing')
@login_required
def weekly_ongoing():
    """每周进行中合作 - 重定向到新路由"""
    return redirect(url_for('statistics.weekly_ongoing'))


@main_bp.route('/weekly_minmax')
@login_required
def weekly_minmax():
    """每周最长最短 - 重定向到新路由"""
    return redirect(url_for('statistics.weekly_minmax'))


@main_bp.route('/report_generation')
@login_required
def report_generation():
    """报表生成 - 重定向到新路由"""
    return redirect(url_for('reports.report_generation'))


@main_bp.route('/attendance_management')
@login_required
def attendance_management():
    """考勤管理 - 重定向到新路由"""
    return redirect(url_for('attendance.attendance_management'))
